<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Service;

use Doctrine\ORM\EntityManager;
use Goods\Entity\Goods;

class GoodsManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 添加商品基本信息
     * @param array $data
     * @return Goods
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addGoods(array $data)
    {
        $goods = new Goods();

        $weightUnit = explode('|', $data['goodsWeightConversion']);
        $goods->setGoodsWeightConversion(intval($weightUnit[0]));
        $goods->setGoodsWeightUnit($weightUnit[1]);
        unset($data['goodsWeightConversion']);

        $goods->valuesSet($data);
        $goods->setGoodsAddTime(time());

        $this->entityManager->persist($goods);
        $this->entityManager->flush();

        return $goods;
    }

    /**
     * 编辑商品基本信息
     * @param array $data
     * @param Goods $goods
     * @return Goods
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editGoods(array $data, Goods $goods)
    {
        if(isset($data['goodsWeightConversion'])) {
            $weightUnit = explode('|', $data['goodsWeightConversion']);
            $goods->setGoodsWeightConversion($weightUnit[0]);
            $goods->setGoodsWeightUnit($weightUnit[1]);
            unset($data['goodsWeightConversion']);
        }

        $goods->valuesSet($data);

        $this->entityManager->flush();

        return $goods;
    }

    /**
     * 商品查看次数更新
     * @param $goodsId
     */
    public function updateGoodsClick($goodsId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(Goods::class, 'g')->set('g.goodsClick', 'g.goodsClick+1')
            ->where('g.goodsId = :goodsId')->setParameter('goodsId', $goodsId);
        $qb->getQuery()->execute();
    }

    /**
     * 商品删除
     * @param Goods $goods
     * @return bool
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteGoods(Goods $goods)
    {
        $this->entityManager->remove($goods);
        $this->entityManager->flush();

        return true;
    }
}